package com.atguigu.juc.t8;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Restaurant {
    //创建锁
    Lock lock = new ReentrantLock();
    //得到三个锁的唤醒标志
    final Condition cutSingal = lock.newCondition();
    final Condition cookSingal = lock.newCondition();
    final Condition sendSingal = lock.newCondition();

    //设置初始状态
    String status = "cut";

    //切菜方法
    public void cut() {
        try {
            lock.lock();
            while (!status.equals("cut")) {
                try {
                    cutSingal.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(Thread.currentThread().getName() + "开始切菜...");
            //切菜切一段时间
            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(2) + 1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            status = "cook";
            cookSingal.signal();
        } finally {
            lock.unlock();
        }
    }

    //炒菜方法
    public void cook() {
        try {
            lock.lock();
            while (!status.equals("cook")) {
                try {
                    cookSingal.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(Thread.currentThread().getName() + "开始炒菜+++");
            //切菜切一段时间
            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(2) + 1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            status = "send";
            sendSingal.signal();
        } finally {
            lock.unlock();
        }
    }

    //传菜方法
    public void send() {
        try {
            lock.lock();
            while (!status.equals("send")) {
                try {
                    sendSingal.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(Thread.currentThread().getName() + "开始传菜===");
            //切菜切一段时间
            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(2) + 1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            status = "cut";
            cutSingal.signal();
        } finally {
            lock.unlock();
        }
    }
}
